package com.xxgc.mq.message;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Map;
import java.util.Random;

/**
 *
 *
 * @Author:何包蛋H
 * @Date：2023/12/4 9:17
 */

@Component
public class RabbitMQSPZ {

    /**
     * 当监听队列有消息的时候，就会把消息给RabbitHandler注解标记的方法
     */

    @RabbitListener(queues = "study_queue")// 监听的队列名称
    public void listenMessage(Message message, Channel channel) throws IOException, ClassNotFoundException {
        //消息序号每次信息MQ会自动+1
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        /**-------------------------用于获取参数-----------*/
        byte[] bytes = message.getBody();
        ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Map map = (Map) inputStream.readObject();

        /**-------------------------里处理业务逻辑-----------*/
        int i = new Random().nextInt(100);
        if (i % 3 == 0){
            channel.basicNack(deliveryTag,true,true);//第一个：消息序号、第二个：是否可以拒签多个消息、第三个：消息是否重回队列
            System.out.printf("业务报错，拒绝签收"+map.toString());
        }else{
            channel.basicAck(deliveryTag,true);
            System.out.println("已签收");
        }


    }

}
